package hash.hashmap7;

import java.io.Serializable;
import java.util.*;


public class DiyHashMap7<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable {
    //默认数组大小
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    //最大数组大小
    static final int MAXIMUM_CAPACITY = 1 << 30;
    //负载因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    //空链表
    static final Entry<?, ?>[] EMPTY_TABLE = {};
    //初始化空的Hash数组 用于存放具体数值
    transient Entry<K, V>[] table = (Entry<K, V>[]) EMPTY_TABLE;
    //元素数量
    transient int size;
    //扩容阀值
    int threshold;
    //负载因子
    final float loadFactor;
    //解决遍历HashMap同时另一个线程修改了
    transient int modCount;


    public DiyHashMap7() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

    public DiyHashMap7(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " + loadFactor);

        this.loadFactor = loadFactor;
        threshold = initialCapacity;
    }


    public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            //初始化table数组
            inflateTable(threshold);
        }
        //空值特殊处理
        if (key == null)
            return putForNullKey(value);

        int hash = Utils.hash(key);
        int i = Utils.indexFor(hash, table.length);

        //如果重复添加 key那么覆盖
        for (Entry<K, V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }


    void addEntry(int hash, K key, V value, int bucketIndex) {
        //数量大于阀值，并且数组索引位置 不等于空（放的位置刚好是个链表） 这里古怪
        if ((size >= threshold) && (null != table[bucketIndex])) {
            //扩容 数组大小为之前的两倍
            resize(2 * table.length);
            //?
            hash = (null != key) ? Utils.hash(key) : 0;
            //重新计算数组下标
            bucketIndex = Utils.indexFor(hash, table.length);
        }

        //创建元素
        createEntry(hash, key, value, bucketIndex);
    }


    void resize(int newCapacity) {
        Entry[] oldTable = table;
        int oldCapacity = oldTable.length;
        //如果数组大小超过阀值不进行扩容
        if (oldCapacity == MAXIMUM_CAPACITY) {
            threshold = Integer.MAX_VALUE;
            return;
        }

        //创建新的数组
        Entry[] newTable = new Entry[newCapacity];
        //将久的数组元素转移
        //transfer(newTable, initHashSeedAsNeeded(newCapacity));
        transfer(newTable, true);
        table = newTable;
        threshold = (int) Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    }


    //将久的数组元素转移
    void transfer(Entry[] newTable, boolean rehash) {
        int newTableLength = newTable.length;
        //循环旧数组每个元素
        for (Entry<K, V> e : table) {
            while (null != e) {
                Entry<K, V> next = e.next;
                if (rehash) {
                    e.hash = null == e.key ? 0 : Utils.hash(e.key);
                }
                int i = Utils.indexFor(e.hash, newTableLength);
                //插入到链表头部
                e.next = newTable[i];
                newTable[i] = e;
                //下一个节点继续循环
                e = next;
            }
        }
    }

    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K, V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }


    //添加空值
    private V putForNullKey(V value) {
        //数组第0个位置存放key空值
        for (Entry<K, V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }


    public V get(Object key) {
        //如果key 等于null 那么获取数组0 位置的 元素
        if (key == null)
            return getForNullKey();
        Entry<K, V> entry = getEntry(key);

        return null == entry ? null : entry.getValue();
    }


    final Entry<K, V> getEntry(Object key) {
        if (size == 0) {
            return null;
        }
        int hash = (key == null) ? 0 : Utils.hash(key);
        //找到数组下表后循环链表
        for (Entry<K, V> e = table[Utils.indexFor(hash, table.length)]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }

    private V getForNullKey() {
        if (size == 0) {
            return null;
        }
        for (Entry<K, V> e = table[0]; e != null; e = e.next) {
            if (e.key == null)
                return e.value;
        }
        return null;
    }


    /**
     * 初始化数组
     */
    private void inflateTable(int toSize) {
        // Find a power of 2 >= toSize
        int capacity = Utils.roundUpToPowerOf2(toSize, MAXIMUM_CAPACITY);
        // 计算扩容阀值
        threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
        table = new Entry[capacity];
        //initHashSeedAsNeeded(capacity);
    }

    @Override
    public Set<Map.Entry<K, V>> entrySet() {
        return null;
    }

    /**
     * Entry 链表
     * @param <K>
     * @param <V>
     */
    static class Entry<K, V> implements Map.Entry<K, V> {
        final K key;
        V value;
        int hash;
        Entry<K, V> next;

        Entry(int h, K k, V v, Entry<K, V> n) {
            value = v;
            next = n;
            key = k;
            hash = h;
        }

        public final K getKey() {
            return key;
        }

        public final V getValue() {
            return value;
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

        public final boolean equals(Object o) {
            if (!(o instanceof Map.Entry))
                return false;
            Map.Entry e = (Map.Entry) o;
            Object k1 = getKey();
            Object k2 = e.getKey();
            if (k1 == k2 || (k1 != null && k1.equals(k2))) {
                Object v1 = getValue();
                Object v2 = e.getValue();
                if (v1 == v2 || (v1 != null && v1.equals(v2)))
                    return true;
            }
            return false;
        }

        public final int hashCode() {
            return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
        }

        public final String toString() {
            return getKey() + "=" + getValue();
        }


        void recordAccess(DiyHashMap7<K, V> m) {
        }


        void recordRemoval(DiyHashMap7<K, V> m) {
        }
    }

}
